package com.example.androidproject.widget.interfaces

import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import com.hyg.base.utils.TouchUtils

/**
 * FileName: OnSingleOrLongClickCallback
 * Author: huangyuguang
 * Date: 2022/6/30
 * Description: 长按事件处理（如长按自加1）
 */
abstract class OnSingleOrLongClickCallback {

    var startTime = 0L
    var minLongClickTime = 500L
    var isLongClicked = false
    var isPressDown = false
    var isRunnableFinish = true
    var view: View?=null

    fun init(){
        TouchUtils.setOnTouchListener(view, object : TouchUtils.OnTouchUtilsListener() {
            override fun onDown(view: View?, x: Int, y: Int, event: MotionEvent?): Boolean {
                startTime = System.currentTimeMillis()
                isPressDown = true
                isLongClicked = false
                if(isRunnableFinish){
                    handler.postDelayed(runnable, minLongClickTime)
                    isRunnableFinish = false
                }
                return true
            }

            override fun onMove(view: View?, direction: Int, x: Int, y: Int, dx: Int, dy: Int, totalX: Int, totalY: Int, event: MotionEvent?): Boolean {
                return true
            }

            override fun onStop(view: View?, direction: Int, x: Int, y: Int, totalX: Int, totalY: Int, vx: Int, vy: Int, event: MotionEvent?): Boolean {
                isPressDown = false
                handler.removeCallbacks(runnable)
                isRunnableFinish = true
                callback(view,true)
                return true
            }
        })

    }

    var handler = Handler(Looper.getMainLooper())
    var runnable = object : Runnable {
        override fun run() {
            if(isPressDown){
                if (isLongClicked){
                    callback(view,false)
                }else{
                    isLongClicked = true
                }
                handler.postDelayed(this, 100)
            }else{
                isRunnableFinish = true
            }
        }

    }

    abstract fun callback(view: View?, isStop: Boolean)
}